package com.sskj.gocoin.v.fragment;

import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.util.ToastUtil;
import com.sskj.common.widget.ViewPagerSlide;
import com.sskj.gocoin.FabiRecordActivity;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.adapter.MyFragmentPagerAdapter;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.rxbus2.RxBus;
import com.sskj.gocoin.common.rxbus2.Subscribe;
import com.sskj.gocoin.common.rxbus2.ThreadMode;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.m.bean.rxbus.TabChange;
import com.sskj.gocoin.p.fragment.FabiFragmentPresenter;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.v.activity.FabiDetailActivity;
import com.sskj.gocoin.v.activity.FabiPublishActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.SellerApplyActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.RConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

@Route(path = RConfig.FABI_FRAGMENT)
public class FabiFragment extends BaseFragment<MainActivity, FabiFragmentPresenter> {

//    @BindView(R2.id.iv_right_end)
//    LinearLayout ivRightEnd;  // 右侧图标  发布出售-发布购买
    //    @BindView(R2.id.iv_right_start)  // 第一个图标  从左侧开始看
//            ImageView ivRightStart;
    @BindView(R2.id.tv_buy)
    TextView tvBuy;
    @BindView(R2.id.tv_sell)
    TextView tvSell;
    //    @BindView(R2.id.tv_record)
//    TextView tvRecord;
//    @BindView(R2.id.view_left)
//    View viewLeft;
//    @BindView(R2.id.view_middle)
//    View viewMiddle;
//    @BindView(R2.id.view_right)
//    View viewRight;
    @BindView(R2.id.viewPager)
    ViewPagerSlide viewPager;
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.iv_fabu)
    ImageView ivFabu;
    @BindView(R2.id.iv_record)
    ImageView ivRecord;
    private UserData userData;
    private AlertDialog tipDialog;
    private AlertDialog cancleTipDialog;
    //购买大厅false，出售大厅true
    private boolean isBuy = false;

    public static FabiFragment newInstance() {
        Bundle args = new Bundle();
        FabiFragment fragment = new FabiFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_fabi;
    }

    @Override
    public FabiFragmentPresenter getPresenter() {
        return new FabiFragmentPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
//        if (LanguageUtil.getAppLanguage(getContext()).equals("zh")) {
//            ivRightEnd.setImageResource(R.mipmap.icon_fabu_jy);
//        } else {
//            ivRightEnd.setImageResource(R.mipmap.fabu_jy_english);
//        }
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        RxBus.getDefault().register(this);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(FabiBuyAndSellFragment.newInstance(false));
        fragments.add(FabiBuyAndSellFragment.newInstance(true));
//        fragments.add(FabiRecordFragment.newInstance());
        viewPager.setSlide(false);
        viewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), fragments));
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                changeTextColor(position);
            }
        });
        ClickUtil.click(tvBuy, () -> {
            if (userData == null) {//是否登录
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiFragment200));
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
//            if (!googleBingTip()) {
//                return;
//            }
            isBuy = false;
            changeTab(new TabChange(false));
        });
        ClickUtil.click(tvSell, () -> {
            if (userData == null) {//是否登录
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiFragment200));
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
//            if (!googleBingTip()) {
//                return;
//            }
            isBuy = true;
            changeTab(new TabChange(true));
        });
//        ClickUtil.click(tvRecord, () -> {
//            if (userData == null) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiBuyAndSellFragment205));
//                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
//                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
//                return;
//            }
//            changeTab(null);
//        });
        ClickUtil.click(ivRecord, () -> {
            if (userData == null) {//是否登录
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiFragment200));
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
            //谷歌绑定
            if (!googleBingTip()) {
                return;
            }
            //跳转记录页面
//            FabiDetailActivity.start(getActivity());
            FabiRecordActivity.start(getActivity());
        });
        ClickUtil.click(ivFabu, () -> {
            if (userData == null) {//是否登录
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strFabiFragment200));
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
            //谷歌绑定
            if (!googleBingTip()) {
                return;
            }
            if (!checkIdent(getActivity())) {//是否实名认证
                return;
            }
            if (userData.getConfig().getPayment_password_set() == 0) {//是否设置资金密码
                com.sskj.gocoin.utils.ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity218));
                ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
                return;
            }
            if (userData.getIs_shop() == 0) {//是否是商家
                showTip();
                return;
            } else if (userData.getIs_shop() == 2) {
                ToastUtil.showShort("商家审核中");
                return;
            }
            if (!checkIdentHign(getActivity())) {
                return;
            }
            FabiPublishActivity.start(getContext(),isBuy);
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(TabChange tabChange) {
        int i;
        if (tabChange == null) {
            i = 2;
//            ivRightEnd.setVisibility(View.GONE);
        } else {
            i = tabChange.isBuy() ? 1 : 0;
//            ivRightEnd.setVisibility(View.VISIBLE);
        }
        changeTextColor(i);
        if (viewPager.getCurrentItem() != i) {
            viewPager.setCurrentItem(i, true);
        }
    }

    /**
     * 谷歌绑定
     */
    private boolean googleBingTip(){
        if (userData.getConfig().getGoogle_bind() == 0) {
            TipUtil.googleBindTip(getActivity(), getString(R.string.lib_google_bind), () -> {
                ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
            });
            return false;
        } else {
            return true;
        }
    }

    /**
     * 更改选项卡
     *
     * @param position
     */
    private void changeTextColor(int position) {
        tvBuy.setBackground(getResources().getDrawable(position == 0 ? R.drawable.bg_blue_background : R.drawable.bg_blue_line));
        tvSell.setBackground(getResources().getDrawable(position == 1 ? R.drawable.bg_blue_background : R.drawable.bg_blue_line));
        tvBuy.setTextColor(getResources().getColor(position == 0 ? R.color.white : R.color.commonSelectColor));
        tvSell.setTextColor(getResources().getColor(position == 1 ? R.color.white : R.color.commonSelectColor));
//        tvRecord.setTextColor(getResources().getColor(position == 2 ? R.color.white : R.color.fabi_item_text_color));

    }

    /**
     * 显示申请商家的提示
     */
    private void showTip() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity());
        View view = View.inflate(getActivity(), R.layout.dialog_fabi_apply, null);
        bottomSheetDialog.setContentView(view);
        ClickUtil.click(view.findViewById(R.id.tv_apply), () -> {
            bottomSheetDialog.dismiss();
            SellerApplyActivity.start(getActivity());
        });
        bottomSheetDialog.setCancelable(true);
        bottomSheetDialog.show();
//        if (tipDialog == null) {
//            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//            View view = View.inflate(getActivity(), R.layout.dialog_fabi_apply, null);
//            ClickUtil.click(view.findViewById(R.id.tv_apply), () -> {
//                tipDialog.dismiss();
//                SellerApplyActivity.start(getActivity());
//            });
//            builder.setView(view);
//            builder.setCancelable(true);
//            tipDialog = builder.create();
//        }
//
//        tipDialog.show();
    }

    /**
     * 显示解除商家认证
     */
    private void showCancleTip() {
        if (cancleTipDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            View view = View.inflate(getActivity(), R.layout.dialog_fabi_cancle_seller_tip, null);
            ClickUtil.click(view.findViewById(R.id.tv_cancel), () -> {
                cancleTipDialog.dismiss();
            });
            ClickUtil.click(view.findViewById(R.id.tv_apply), () -> {
                cancleTipDialog.dismiss();
                SellerApplyActivity.start(getActivity());
            });
            builder.setView(view);
            builder.setCancelable(true);
            cancleTipDialog = builder.create();
        }

        cancleTipDialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            userViewModel.update();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        userViewModel.update();
    }
}
